'''
Gets the device serial numbers from the CBTS PDF invoices, for HP Blue Carpet claims.
'''
import os
import re
from datetime import datetime
from dateparser import parse as dateparser_parse
import PySimpleGUI as sg
from openpyxl import Workbook
import PyPDF2

sg.theme('Reddit')


def get_invoice_date(invoice_path):
    '''Gets the invoice date for the claim, from its PDF file.'''
    date_regex = re.compile(r'\d{1,2}/\d{1,2}/\d{2,4}')

    pdf_file_obj = open(invoice_path, 'rb')
    pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
    num_pages = pdf_reader.numPages

    for i in range(num_pages):
        page = pdf_reader.getPage(i)

        try:
            found_date = dateparser_parse(
                date_regex.search( page.extractText() ).group()
            )
        except AttributeError:
            continue
        else:
            today = datetime.now()

            if found_date:
                days_open = (today - found_date).days

                if days_open > 60:
                    sg.popup_error(
                        'The invoice must be submitted within 60 days of being created!',
                        title='Error'
                    )
                    return

                return found_date


def get_invoice_num(invoice_path):
    '''Gets the invoice number for the claim, from its PDF file.'''
    invoice_num_regex = re.compile(r'INV-\d+-1', re.I)

    pdf_file_obj = open(invoice_path, 'rb')
    pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
    num_pages = pdf_reader.numPages

    for i in range(num_pages):
        page = pdf_reader.getPage(i)

        try:
            found_invoice_num = invoice_num_regex.search( page.extractText() ).group()
        except AttributeError:
            continue
        else:
            return found_invoice_num


def get_po_num(invoice_path):
    '''Gets the invoice date for the claim, from its PDF file.'''
    po_num_regex = re.compile(r'\d{8}')

    pdf_file_obj = open(invoice_path, 'rb')
    pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
    num_pages = pdf_reader.numPages

    for i in range(num_pages):
        page = pdf_reader.getPage(i)

        try:
            found_po_num = po_num_regex.search( page.extractText() ).group()
        except AttributeError:
            continue
        else:
            return found_po_num


def get_serials(invoice_path):
    '''Gets a list of all the serials for the claim, from its PDF file.'''
    serials = []

    sn_regex = re.compile(r'MXL\w+|5CD\w+|5CG\w+|8CG\w+|2UA\w+', re.I)

    pdf_file_obj = open(invoice_path, 'rb')
    pdf_reader = PyPDF2.PdfFileReader(pdf_file_obj)
    num_pages = pdf_reader.numPages

    for i in range(num_pages):
        page = pdf_reader.getPage(i)
        matching_serials = sn_regex.findall( page.extractText() )
        serials += matching_serials

    return serials


def create_template_file(serials, pn, invoice_num, invoice_path):
    '''
    Creates the Excel workbook template for the HP Blue Carpet serial numbers.
    '''
    wb = Workbook()
    ws = wb.active
    ws.title = "Template"

    ws['A1'] = 'SKU'
    ws['B1'] = 'SerialNumber'

    for i, serial in enumerate(serials, 2):
        ws[f'A{i}'] = pn
        ws[f'B{i}'] = serial

    template_path = os.path.join(
        os.path.dirname(invoice_path), f'{invoice_num} - Template.xlsx'
    )
    wb.save(template_path)
    return template_path
